import fs from "node:fs";
import path from "node:path";
import css from "@webref/css";
import { camelCaseToDashed } from "../lib/utils/camelize.js";

const parsedFiles = await css.listAll();
const definitions = new Map();
for (const { properties } of Object.values(parsedFiles)) {
  if (Array.isArray(properties)) {
    for (const definition of properties) {
      const { name } = definition;
      if (name) {
        definitions.set(name, definition);
      }
    }
  }
}

const { dirname } = import.meta;
const dashedProperties = fs
  .readdirSync(path.resolve(dirname, "../lib/properties"))
  .filter((propertyFile) => path.extname(propertyFile) === ".js")
  .map((propertyFile) => camelCaseToDashed(path.basename(propertyFile, ".js")))
  .toSorted();

const implementedProperties = new Map();
for (const property of dashedProperties) {
  const definition = definitions.get(property);
  implementedProperties.set(property, definition);
}

const outputFile = path.resolve(dirname, "../lib/generated/implementedProperties.js");

const dateToday = new Date();
const [dateTodayFormatted] = dateToday.toISOString().split("T");
const output = `"use strict";
// autogenerated - ${dateTodayFormatted}

module.exports = new Map(${JSON.stringify([...implementedProperties], null, 2)});
`;

fs.writeFileSync(outputFile, output);
